package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.abvice.LogOperation;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.EmpLogService;
import com.itheima.service.EmpService;

import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpExprMapper empExprMapper;
    @Autowired
    private EmpLogService empLogService;
    @Autowired
    private DeptMapper deptMapper;

    public EmpServiceImpl() {
        log.error("EmpServiceImpl被创建");
    }

    @Override
    public PageResult<Emp> page(EmpQueryParam empQueryParam) {
        //1.创建一个page对象
        Page<Emp> page = new Page<>(empQueryParam.getPage(), empQueryParam.getPageSize());
        //构建条件
        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
        if (empQueryParam.getName() != null && !"".equals(empQueryParam.getName())) {
            queryWrapper.like(Emp::getName, empQueryParam.getName());
        }
        if (empQueryParam.getGender() != null) {
            queryWrapper.eq(Emp::getGender, empQueryParam.getGender());
        }
        if (empQueryParam.getBegin() != null && empQueryParam.getEnd() != null) {
            queryWrapper.between(Emp::getEntryDate, empQueryParam.getBegin(), empQueryParam.getEnd());
        }
//2.执行MP分页查询

        // 1.设置分页参数
        PageHelper.startPage(empQueryParam.getPage(), empQueryParam.getPageSize());
//        // 2.执行查询
        List<Emp> empList = empMapper.list(empQueryParam);
        // 3.解析查询结果,并封装返回
        Page<Emp> p = (Page<Emp>) empList;
        return new PageResult<>(p.getTotal(), p.getResult());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean save(Emp emp) {
        // 1.补全创建和最后更改的时间
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setPassword("123456");
        // 2.调用empMapper保存emp
        empMapper.insert(emp);
        // 3.批量保存员工的工作经历
        Integer empId = emp.getId();
        List<EmpExpr> exprList = emp.getExprList();
        if (!CollectionUtils.isEmpty(exprList)) {
            exprList.forEach(empExpr -> empExpr.setEmpId(empId));
            empExprMapper.insertBatch(exprList);
        }
        return false;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<Integer> ids) {
        // 1.删除员工的基本信息
        empMapper.deleteBatchIds(ids);
        // 2.删除员工的工作经历信息
        empExprMapper.deleteByEmpids(ids);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Emp findById(Integer id) {
        // 1.查询员工的基本信息
        Emp emp = empMapper.selectById(id);
        // 2.查询员工的工作经历
        List<EmpExpr> empExprList = empExprMapper.findByEmpid(id);
        // 3.将两个信息封装一起并返回
        emp.setExprList(empExprList);
        return emp;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    @LogOperation
    public void update(Emp emp) {
        // 1.根据id修改员工信息
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.updateById(emp);
        // 2.根据id修改员工经历信息
        // 2.1先把原来的删除掉
        empExprMapper.deleteByEmpids(Collections.singletonList(emp.getId()));
        // 2.2再添加新的
        List<EmpExpr> exprList = emp.getExprList();
        if (!CollectionUtils.isEmpty(exprList)) {
            exprList.forEach(empExpr -> empExpr.setEmpId(emp.getId()));
            empExprMapper.insertBatch(exprList);
        }
    }

    @Override
    public List<Emp> listAll() {
        return empMapper.selectList(null);
    }

    @Override
    public LoginInfo login(Emp emp) {
        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Emp::getUsername, emp.getUsername()).eq(Emp::getPassword, emp.getPassword());
        Emp resultEmp = empMapper.selectOne(queryWrapper);
        if (resultEmp != null) {
            log.info("用户登录成功:{}", resultEmp);
            // 用户登录成功生成一个令牌
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", resultEmp.getId());
            claims.put("username", resultEmp.getUsername());
            String jwt = JwtUtils.generateToken(claims);
            return new LoginInfo(resultEmp.getId(), resultEmp.getUsername(), resultEmp.getName(), jwt);
        }
        return null;
    }
}
